/**
 * 
 */
package nl.boektrust.btsoep.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import nl.boektrust.btsoep.shared.model.AvailabilityCode;
import nl.boektrust.btsoep.shared.model.ContentSpecifier;
import nl.boektrust.btsoep.shared.model.ContentSpecifierType;
import nl.boektrust.btsoep.shared.model.Contributor;
import nl.boektrust.btsoep.shared.model.ContributorRoleCode;
import nl.boektrust.btsoep.shared.model.EditionTypeCode;
import nl.boektrust.btsoep.shared.model.ISBN;
import nl.boektrust.btsoep.shared.model.ISBNReference;
import nl.boektrust.btsoep.shared.model.ISBNReferenceType;
import nl.boektrust.btsoep.shared.model.LanguageCode;
import nl.boektrust.btsoep.shared.model.Person;
import nl.boektrust.btsoep.shared.model.PhysicalBookManifestation;
import nl.boektrust.btsoep.shared.model.Price;
import nl.boektrust.btsoep.shared.model.PriceTypeCode;
import nl.boektrust.btsoep.shared.model.ProductFormCode;
import nl.boektrust.btsoep.shared.model.Supplier;
import nl.boektrust.btsoep.shared.model.SupplyDetail;
import nl.boektrust.btsoep.shared.model.URLReference;
import nl.boektrust.btsoep.shared.model.URLReferenceType;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * @author rao3
 *
 */
public class EditBookDialog extends DialogBox implements  ChangeHandler, KeyUpHandler,
		KeyDownHandler, ValueChangeHandler<String> {
	BoekenPanel panel;
	PersistentServiceAsync persistentService;
	HorizontalPanel buttonPanel = new HorizontalPanel();
	Button okButton = new Button("OK");
	Button cancelButton = new Button("Annuleer");
	final ArrayList<Person> destinationArrayList = new ArrayList<Person>();
	// panel arrays for repeatable fields
	final ArrayList <EditBookContributorPanel> contributorPanels = new ArrayList<EditBookContributorPanel>();
	final ArrayList <EditBookSubjectPanel> subjectPanels = new ArrayList<EditBookSubjectPanel>();
	final ArrayList <EditBookVerwijzingenISBNPanel> isbnPanels = new ArrayList<EditBookVerwijzingenISBNPanel>();
	final ArrayList <EditBookVerwijzingenURLPanel> urlPanels = new ArrayList<EditBookVerwijzingenURLPanel>();
	final DialogBox waitDialogBox = new DialogBox();

	// UI panels
	EditBookVerticalPanelSimpleTextbox isbn13Panel = new EditBookVerticalPanelSimpleTextbox("ISBN13", this) {
		@Override 
		boolean hasInvalidData() {
			if (ISBN.isValidISBN13((String)value) == true) {
				return false;
			} 
			return true;
		}
	};
	EditBookVerticalPanelSimpleTextbox titelPanel = new EditBookVerticalPanelSimpleTextbox("Titel", this);
	EditBookVerticalPanelSimpleTextbox subtitelPanel = new EditBookVerticalPanelSimpleTextbox("Subtitel", this);
	EditBookVerticalPanelSimpleTextbox oorspronkelijkeTitelPanel = new EditBookVerticalPanelSimpleTextbox("Oorspronkelijke titel", this);
	EditBookVerticalPanelSimpleTextbox imprintPanel = new EditBookVerticalPanelSimpleTextbox("Imprint", this);
	EditBookVerticalPanelSimpleTextbox setTitelPanel = new EditBookVerticalPanelSimpleTextbox("Set-titel", this);
	EditBookVerticalPanelSimpleTextboxInteger vbpPanel = new EditBookVerticalPanelSimpleTextboxInteger("Vaste boekenprijs", this)  {
		@Override String labelFormatter(int i) {
			if (value % 100 <= 9) {
				return "EUR. " + new Integer((value/100)).toString() + ",0"+new Integer((value%100)).toString();
			}
			return "EUR. " + new Integer((value/100)).toString() + ","+new Integer((value%100)).toString();
		}
	};
	EditBookVerticalPanelSimpleTextboxInteger adviesprijsPanel = new EditBookVerticalPanelSimpleTextboxInteger("Advies boekenprijs", this) {
		@Override String labelFormatter(int i) {
			if (value % 100 <= 9) {
				return "EUR. " + new Integer((value/100)).toString() + ",0"+new Integer((value%100)).toString();
			}
			return "EUR. " + new Integer((value/100)).toString() + ","+new Integer((value%100)).toString();
		}
	};
	EditBookVerticalPanelSimpleTextbox serieTitelPanel = new EditBookVerticalPanelSimpleTextbox("Serie-titel", this);
	EditBookVerticalPanelSimpleTextboxInteger aantalPaginasPanel = new EditBookVerticalPanelSimpleTextboxInteger("Aantal pagina's", this);
	EditBookVerticalPanelSimpleTextboxInteger gewichtPanel = new EditBookVerticalPanelSimpleTextboxInteger("Gewicht", this) {
		@Override String labelFormatter(int i) {
			return new Integer(value).toString() + " gram";
		}
	};
	EditBookVerticalPanelSimpleDate publicatiedatumPanel = new EditBookVerticalPanelSimpleDate("Publicatiedatum", this);
	EditBookVerticalPanelSimpleDate eerstepublicatiedatumPanel = new EditBookVerticalPanelSimpleDate("Eerste publicatiedatum", this);
	EditBookVerticalPanelSimpleDate datumEersteWijzigingPanel = new EditBookVerticalPanelSimpleDate("Datum eerste wijziging", this);
	EditBookVerticalPanelSimpleDate datumLaatsteWijzigingPanel = new EditBookVerticalPanelSimpleDate("Datum laatste wijziging", this);
	EditBookVerticalPanelSimpleListbox taalPanel = new EditBookVerticalPanelSimpleListbox("Taal", this);
	EditBookVerticalPanelSimpleListbox oorspronkelijketaalPanel = new EditBookVerticalPanelSimpleListbox("Oorspronkelijke taal", this);
	EditBookVerticalPanelSimpleListbox productvormPanel = new EditBookVerticalPanelSimpleListbox("Product vorm", this);
	EditBookVerticalPanelSimpleListbox drukPanel = new EditBookVerticalPanelSimpleListbox("Druk", this);
	EditBookVerticalPanelSimpleListbox editiePanel = new EditBookVerticalPanelSimpleListbox("Editie", this);
	EditBookVerticalPanelSimpleListbox beschikbaarCB = new EditBookVerticalPanelSimpleListbox("Beschikbaar CB", this);
	EditBookVerticalPanelSimpleListbox beschikbaarUitgever = new EditBookVerticalPanelSimpleListbox("Beschikbaar Uitgever", this);
	EditBookVerticalPanelSimpleListbox beschikbaarScholtens = new EditBookVerticalPanelSimpleListbox("Beschikbaar Scholtens", this);
	EditBookVerticalPanelSimpleListbox beschikbaarLibris = new EditBookVerticalPanelSimpleListbox("Beschikbaar Libris", this);
	EditBookVerticalPanelSimpleListbox uitgeverPanel = new EditBookVerticalPanelSimpleListbox("Uitgever", this);

	EditBookGeillustreerdPanel geillustreerdPanel = new EditBookGeillustreerdPanel("Geillustreerd", this);
	EditBookAfmetingenPanel afmetingenPanel = new EditBookAfmetingenPanel("Afmetingen", this);
	
	SimplePanel gridPanel = new SimplePanel();
	VerticalPanel vPanel = new VerticalPanel();
	PhysicalBookManifestation bookmf;
	
	
	public PhysicalBookManifestation readGridPanels() {
		final PhysicalBookManifestation theBookMF = new PhysicalBookManifestation();
		theBookMF.setId(bookmf.getId());

		theBookMF.setIsbn(new ISBN(isbn13Panel.getValue()) );
		theBookMF.setTitle(titelPanel.getValue());
		theBookMF.setSubtitle(subtitelPanel.getValue());
		theBookMF.setOriginalTitle(oorspronkelijkeTitelPanel.getValue());
		theBookMF.setSetTitle(setTitelPanel.getValue());
		theBookMF.setSeriesTitle(serieTitelPanel.getValue());
		theBookMF.setNumberOfPages(aantalPaginasPanel.getIntValue());
		theBookMF.setWeight(gewichtPanel.getIntValue());
		theBookMF.setImprint(imprintPanel.getValue());
		theBookMF.setLanguageCode(LanguageCode.parseStringIntoLanguageCode(taalPanel.getValue()));
		theBookMF.setOriginalLanguageCode(LanguageCode.parseStringIntoLanguageCode(oorspronkelijketaalPanel.getValue()));
		theBookMF.setPublicationDate(publicatiedatumPanel.getDateValue());
		theBookMF.setFirstPublicationDate(eerstepublicatiedatumPanel.getDateValue());
		theBookMF.setProductFormCode(ProductFormCode.parseStringIntoProductFormCode(productvormPanel.getValue()));
		theBookMF.setEditionTypeCode(EditionTypeCode.parseStringIntoEditionTypeCode(editiePanel.getValue()));
		if (drukPanel.getValue().length() > 0) theBookMF.setEdition(new Integer(drukPanel.getValue()));
		theBookMF.setFirstModificationDate(datumEersteWijzigingPanel.getDateValue());
		theBookMF.setModificationDate(datumLaatsteWijzigingPanel.getDateValue());
		theBookMF.setHeight(afmetingenPanel.getHeightInMilimeters());
		theBookMF.setWidth(afmetingenPanel.getWidthInMilimeters());
		theBookMF.setThickness(afmetingenPanel.getThicknessInMilimeters());
		if (geillustreerdPanel.isGeillustreerd() == true) {
			theBookMF.setIllustrated(true);
			theBookMF.setNumberOfBWIllustrations(geillustreerdPanel.getNumBWImages());
			theBookMF.setNumberOfColorIllustrations(geillustreerdPanel.getNumColorImages());
		} else {
			theBookMF.setIllustrated(false);
		}
	
		if (AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarUitgever.getValue()) != AvailabilityCode.UNDEFINED) {
			SupplyDetail s = new SupplyDetail();
			s.setAvailabilityCode(AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarUitgever.getValue()));
			s.setModificationDate(new Date());
			s.addPrice(new Price(vbpPanel.getIntValue(),PriceTypeCode.FIXED));
			s.addPrice(new Price(adviesprijsPanel.getIntValue(), PriceTypeCode.MSRP));
			// TODO: change the name of the publisher here
			s.setSupplier(new Supplier("Uitgever", ""));
			//theBookMF.setaSupplyDetail(s);
			theBookMF.addSupplyDetail(s);
		}
		
		if (AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarLibris.getValue()) != AvailabilityCode.UNDEFINED) {
			SupplyDetail s = new SupplyDetail();
			s.setAvailabilityCode(AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarLibris.getValue()));
			s.setModificationDate(new Date());
			s.addPrice(new Price(vbpPanel.getIntValue(),PriceTypeCode.FIXED));
			s.addPrice(new Price(adviesprijsPanel.getIntValue(), PriceTypeCode.MSRP));
			// TODO: change the name of the publisher here
			s.setSupplier(new Supplier("Libris", ""));
			theBookMF.addSupplyDetail(s);
		}
		if (AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarCB.getValue()) != AvailabilityCode.UNDEFINED) {
			SupplyDetail s = new SupplyDetail();
			s.setAvailabilityCode(AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarCB.getValue()));
			s.setModificationDate(new Date());
			s.addPrice(new Price(vbpPanel.getIntValue(),PriceTypeCode.FIXED));
			s.addPrice(new Price(adviesprijsPanel.getIntValue(), PriceTypeCode.MSRP));
			// TODO: change the name of the publisher here
			s.setSupplier(new Supplier("Centraal Boekhuis", ""));
			theBookMF.addSupplyDetail(s);
		}
		if (AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarScholtens.getValue()) != AvailabilityCode.UNDEFINED) {
			SupplyDetail s = new SupplyDetail();
			s.setAvailabilityCode(AvailabilityCode.parseStringIntoAvailabilityCode(beschikbaarScholtens.getValue()));
			s.setModificationDate(new Date());
			s.addPrice(new Price(vbpPanel.getIntValue(),PriceTypeCode.FIXED));
			s.addPrice(new Price(adviesprijsPanel.getIntValue(), PriceTypeCode.MSRP));
			// TODO: change the name of the publisher here
			s.setSupplier(new Supplier("Scholtens", ""));
			theBookMF.addSupplyDetail(s);
		}
		
		//for (EditBookPanel panel : rightColumnPanels) {
		for (EditBookContributorPanel panel : contributorPanels) {
			if (panel.getContributor().getRoleCode() != ContributorRoleCode.UNDEFINED) {
				if (panel.getContributor().getNameOnBook().length() > 0) {
					theBookMF.addContributor(panel.getContributor());
				}
			}
		}
		
		for (EditBookSubjectPanel panel : subjectPanels) {
			ContentSpecifierType contentSpecifierType = ((EditBookSubjectPanel)panel).getContentSpecifier().getContentSpecifierType();
			if (contentSpecifierType != ContentSpecifierType.UNDEFINED) {
				if (contentSpecifierType == ContentSpecifierType.NUGICODE || contentSpecifierType == ContentSpecifierType.NURCODE) {
					if (((EditBookSubjectPanel)panel).getContentSpecifier().getCode() != -1) {
						theBookMF.addContentSpecifier(((EditBookSubjectPanel)panel).getContentSpecifier());
					}

				} else if (contentSpecifierType == ContentSpecifierType.GEOCODE) {
					try {
						if (((EditBookSubjectPanel)panel).getContentSpecifier().getDescription().length() > 0) {
							theBookMF.addContentSpecifier(((EditBookSubjectPanel)panel).getContentSpecifier());
						}
					} catch (Exception e) {
						System.err.println("EditBookDialog:onClick(): Exception: while trying to store EditBookSubjectPanel contents: contentSpecifier is GEOCODE, but contentspecifier.description is NULL (should be initialized).");
						e.printStackTrace();
					}
				}
			}			
		}
		
		for (EditBookVerwijzingenISBNPanel panel : isbnPanels) {
			if (panel.getIsbnReference().getIsbnReferenceType() != ISBNReferenceType.UNDEFINED) {
				if (panel.getIsbnReference().getIsbn().isValidISBN13() == true) {
					theBookMF.addISBNReference(((EditBookVerwijzingenISBNPanel)panel).getIsbnReference());

				}
			}
		}
		
		for (EditBookVerwijzingenURLPanel panel : urlPanels) {
			if (panel.getUrlReference().getUrlReferenceType() != URLReferenceType.UNDEFINED) {
				if (panel.getUrlReference().getUrl() != null && panel.getUrlReference().getUrl().length() > 0) {
					theBookMF.addURLReference(((EditBookVerwijzingenURLPanel)panel).getUrlReference());									
				}
			}
		}
	

		return theBookMF;
		
	}
	public void panelHasChanged() {
//		bookmf = readGridPanels();
	//	this.getRighthandArrayList(bookmf);
//		this.getLefthandArrayList(bookmf);
		//this.drawTableInSimplePanel(gridPanel, bookmf);
		if (isbn13Panel.hasInvalidData() == false) {
			okButton.setEnabled(true);
		} else {
			okButton.setEnabled(false);
		}
	}
	
	public void redrawTable() {
		this.drawTableInSimplePanel(gridPanel, bookmf);
	}
	
	public void drawTableInSimplePanel(SimplePanel p, PhysicalBookManifestation bookmf) {
		int numRows = 1;
		//+ p.getIdentifiers().size() +1;
		int rowNum = 0;
		int numColumns = 6;
		//final ArrayList<EditBookPanel> leftColumnPanels = this.getLefthandArrayList(bookmf);
		//final ArrayList<EditBookPanel> rightColumnPanels = this.getRighthandArrayList(bookmf);
		if (p.getWidget() != null) p.remove(p.getWidget());

		Grid g = new Grid(numRows,numColumns);
		
		g.setWidget(rowNum, 0, new Label("Nog niet"));
		

		g.setWidget(rowNum, 1, new Label("Teksten:"));
		g.setWidget(rowNum, 2, new Label(".."));
		rowNum++;
		g.resize(numRows+rowNum, numColumns);

		for (EditBookPanel panel : this.getLefthandArrayList(bookmf)) {
			if (panel == isbn13Panel) g.setWidget(rowNum, 0, new Label("Basis"));
			if (panel == taalPanel) g.setWidget(rowNum, 0, new Label("Talen"));
			if (panel == setTitelPanel) g.setWidget(rowNum, 0, new Label("Verwijzingen"));
			if (panel == productvormPanel) g.setWidget(rowNum, 0, new Label("Fysiek"));
			try {
				g.setWidget(rowNum, 1, panel.getLabel());
				g.setWidget(rowNum, 2, panel);
				rowNum++;
				g.resize(numRows+rowNum, numColumns);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		numRows = rowNum;
		rowNum = 0;

		for (EditBookPanel panel : this.getRighthandArrayList(bookmf)) {
			try {
				g.setWidget(rowNum, 3, panel.getLabel());
				g.setWidget(rowNum, 4, panel);
				rowNum++;
				if (rowNum >= numRows) g.resize(numRows+rowNum, numColumns);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		g.setWidth("1536px");
	    g.getCellFormatter().setWidth(0, 1, "256px");
	    g.getCellFormatter().setWidth(0, 2, "512px");
	    g.getCellFormatter().setWidth(0, 4, "512px");
	    g.getCellFormatter().setWidth(0, 3, "256px");

		p.setWidget(g);
		
	}
	
	public void showWaitDialog() {
		HorizontalPanel hPanel = new HorizontalPanel();
		hPanel.add(new Label("Inladen auteurs"));
		waitDialogBox.setText("Wachten...");
		waitDialogBox.setAnimationEnabled(true);
		waitDialogBox.setGlassEnabled(true);
		waitDialogBox.setWidget(hPanel);
		waitDialogBox.show();
	}
	
	public EditBookDialog(PhysicalBookManifestation argbookmf, BoekenPanel parentPanel) {
		this.bookmf = argbookmf;
		this.setWidth("1600px");
		persistentService = GWT.create(PersistentService.class);
		if (bookmf == null) {
			bookmf = new PhysicalBookManifestation("");
			bookmf.setTitle("");
			bookmf.setId(new Integer(0).longValue());
			bookmf.setFirstModificationDate(new Date());
		}

		this.getAllPersons();

		// Set the dialog box's caption.
		setText("Bewerk gegevens...");

		// Enable animation.
		setAnimationEnabled(true);

		// Enable glass background.
		setGlassEnabled(true);
		
		// build the panel
		vPanel.setWidth("1600px");
		setWidget(vPanel);
		
		//final PhysicalBookManifestation theBoaokMF = new PhysicalBookManifestation();
		//theBookMF.setId(bookmf.getId());
		final BoekenPanel theParentPanel = parentPanel; 

		// add the buttons 
		try {
			okButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					PhysicalBookManifestation pbm = readGridPanels();
					pbm.setModificationDate(new Date());
					pbm.toPrintString();
					persistentService.persistPhysicalBookManifestation(pbm, new AsyncCallback<Void>() {
						//		@Override
						public void onFailure(Throwable caught) {
						//	Log.error("EditBookDialog:okButton/onClick: PersistentService RPC call failed " + caught);
							System.err.println(caught.getMessage());
							caught.printStackTrace();
						}

						//      @Override
						public void onSuccess(Void result) {
							if (theParentPanel != null) theParentPanel.loadData();
						//	Log.debug("theBookMF:okButton/onClick: onClick(): PersistentService RPC call succeeded");

						}

					});
					EditBookDialog.this.hide();
				}
			});
		okButton.setEnabled(false);
		buttonPanel.add(okButton);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Button cancel = new Button("Annuleer");
		cancel.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				// force reload of data, even if nothing has changed, to ensure proper behavior of the row selection mechanism
				//if (parentPanel != null) parentPanel.loadData();

				EditBookDialog.this.hide();
			}
		});
		buttonPanel.add(cancel);

		gridPanel.setVisible(false);
		vPanel.add(gridPanel);
		// add the repeating panels to their respective arrays
		for (ISBNReference isbnReference : bookmf.getIsbnReferences()) {
			isbnPanels.add(new EditBookVerwijzingenISBNPanel(new String("Verwijzingen (ISBN)"), isbnReference, false, this));
		}
		for (URLReference urlReference : bookmf.getUrlReferences()) {
			urlPanels.add(new EditBookVerwijzingenURLPanel(new String("Verwijzingen (URL)"), urlReference, false, this));
		}
		for (Contributor c : bookmf.getContributors()) {
			EditBookContributorPanel panel = new EditBookContributorPanel("Mensen");
			panel.setContributor(c);
			panel.setPersonList(destinationArrayList);
			panel.populatePersonListBox();
			panel.setToDisplayMode();
			contributorPanels.add(new EditBookContributorPanel());
		}
		for (ContentSpecifier c : bookmf.getContentSpecifiers()) {
			subjectPanels.add(new EditBookSubjectPanel(new String("Onderwerpen"), c, false));
		}
		final ArrayList<EditBookPanel> leftColumnPanels = this.getLefthandArrayList(bookmf);
		final ArrayList<EditBookPanel> rightColumnPanels = this.getRighthandArrayList(bookmf);
	
		
		this.populatePanelsInArrayList(leftColumnPanels, bookmf);
		this.populatePanelsInArrayList(rightColumnPanels, bookmf);
		drawTableInSimplePanel(gridPanel, bookmf);
		vPanel.add(buttonPanel);
	}


	/* (non-Javadoc)
	 * @see com.google.gwt.event.logical.shared.ValueChangeHandler#onValueChange(com.google.gwt.event.logical.shared.ValueChangeEvent)
	 */
	public void onValueChange(ValueChangeEvent<String> event) {

	}

	/* (non-Javadoc)
	 * @see com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt.event.dom.client.KeyDownEvent)
	 */
	public void onKeyDown(KeyDownEvent event) {

	}

	/* (non-Javadoc)
	 * @see com.google.gwt.event.dom.client.KeyUpHandler#onKeyUp(com.google.gwt.event.dom.client.KeyUpEvent)
	 */
	public void onKeyUp(KeyUpEvent event) {

	}

	/* (non-Javadoc)
	 * @see com.google.gwt.event.dom.client.ChangeHandler#onChange(com.google.gwt.event.dom.client.ChangeEvent)
	 */
	public void onChange(ChangeEvent event) {

	}

	public void getAllPersons() {
		gridPanel.setVisible(false);
		showWaitDialog();
		//waitDialogBox.show();
		try {
			persistentService.getAllPersons(new AsyncCallback<List<Person>>() {
				//		@Override
				public void onFailure(Throwable caught) {
					System.err.println("MensenPanel.java (person): onClick(): PersistentService RPC call failed " + caught);
				}

				//      @Override
				public void onSuccess(List<Person> result) {
					/*
		                    	Log.debug("getallpersons: success");
		                    	Log.debug("MensenPanel.java (person): onClick(): PersistentService RPC call succeeded; received a list with "+result.size()+" elements");
					 */
					for (Person p : result) {
						destinationArrayList.add(p);

					}
					waitDialogBox.hide();
					gridPanel.setVisible(true);
					redrawTable();
					
				}

			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void populatePanelsInArrayList(ArrayList<EditBookPanel> panels, PhysicalBookManifestation bookmf) {
		AvailabilityCode avail_cb = AvailabilityCode.UNDEFINED;
		AvailabilityCode avail_libris = AvailabilityCode.UNDEFINED;
		AvailabilityCode avail_scholtens = AvailabilityCode.UNDEFINED;
		AvailabilityCode avail_uitgever = AvailabilityCode.UNDEFINED;
		int numIsbnVerwijzingenPanels = 0;
		int numURLVerwijzingenPanels = 0;
		int numContentSpecifiedPanels = 0;
		int numMensenPanels = 0;

		if (bookmf.getSupplyDetails() != null) {
			for (SupplyDetail s : bookmf.getSupplyDetails()) {
				if (s.getSupplier().getName().equals("Centraal Boekhuis")) avail_cb = s.getAvailabilityCode();
				if (s.getSupplier().getName().equals("Scholtens")) avail_scholtens = s.getAvailabilityCode();
				if (s.getSupplier().getName().equals("Libris")) avail_libris = s.getAvailabilityCode();
				if (s.getSupplier().getName().equals("Uitgever")) avail_uitgever = s.getAvailabilityCode();
			}
		}

		for (EditBookPanel panel : panels) {
			// since I use instanceof to compare classes, and ..TextboxInteger is a subclass of ..Textbox, the test 
			// for ..TextboxInteger should always *precede* the one for ..Textbox.
			if (panel instanceof EditBookVerticalPanelSimpleTextboxInteger) {
				if (panel.getLabel().getText().equals("Aantal pagina's")) {
					((EditBookVerticalPanelSimpleTextboxInteger)panel).setValue(bookmf.getNumberOfPages());
				} else if (panel.getLabel().getText().equals("Gewicht")) {
					((EditBookVerticalPanelSimpleTextboxInteger)panel).setValue(bookmf.getWeight());
				} else if (panel.getLabel().getText().equals("Vaste boekenprijs")) {
					((EditBookVerticalPanelSimpleTextboxInteger)panel).setValue(bookmf.getPrice(PriceTypeCode.FIXED));
				} else if (panel.getLabel().getText().equals("Advies boekenprijs")) {
					((EditBookVerticalPanelSimpleTextboxInteger)panel).setValue(bookmf.getPrice(PriceTypeCode.MSRP));
				} else System.err.println("Error: populatePanelsInArrayList found panel of type EditBookVerticalPanelSimpleTextboxInteger with label "+panel.getLabel().getText()+" - don't know how to populate this panel.");
			} else if (panel instanceof EditBookVerticalPanelSimpleTextbox) {
				if (panel.getLabel().getText().equals("ISBN13")) {
					if (bookmf.getIsbn() != null) {
						((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getIsbn().getIsbn13());
					}
				} else if (panel.getLabel().getText().equals("Titel")) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getTitle());
				else if (panel.getLabel().getText().equals("Subtitel")) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getSubtitle());
				else if (panel.getLabel().getText().equals("Oorspronkelijke titel")) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getOriginalTitle());
				else if (panel.getLabel().getText().equals("Set-titel") == true) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getSetTitle());
				else if (panel.getLabel().getText().equals("Serie-titel")) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getSeriesTitle());
				else if (panel.getLabel().getText().equals("Imprint")) ((EditBookVerticalPanelSimpleTextbox)panel).setValue(bookmf.getImprint());
				else System.err.println("Error: populatePanelsInArrayList found panel of type TextBox with label "+panel.getLabel().getText()+" - don't know how to populate this panel.");
			} else if (panel.getClass() == EditBookVerticalPanelSimpleListbox.class) {

				if (panel.getLabel().getText().equals("Taal")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithLanguages(bookmf.getLanguageCode());
				}
				else if (panel.getLabel().getText().equals("Oorspronkelijke taal")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithLanguages(bookmf.getOriginalLanguageCode());
				}
				else if (panel.getLabel().getText().equals("Product vorm")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithProductForm(bookmf.getProductFormCode());
					((EditBookVerticalPanelSimpleListbox)panel).setToDisplayMode();
				}
				else if (panel.getLabel().getText().equals("Editie")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithEdition(bookmf.getEditionTypeCode());
					((EditBookVerticalPanelSimpleListbox)panel).setToDisplayMode();
				}
				else if (panel.getLabel().getText().equals("Druk")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithDruk(bookmf.getEdition());
					((EditBookVerticalPanelSimpleListbox)panel).setToDisplayMode();
				}
				else if (panel.getLabel().getText().equals("Beschikbaar CB")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithAvailability(avail_cb);
				}
				else if (panel.getLabel().getText().equals("Beschikbaar Scholtens")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithAvailability(avail_scholtens);
				}
				else if (panel.getLabel().getText().equals("Beschikbaar Libris")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithAvailability(avail_libris);
				}
				else if (panel.getLabel().getText().equals("Beschikbaar Uitgever")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithAvailability(avail_uitgever);
				} else if (panel.getLabel().getText().equals("Uitgever")) {
					((EditBookVerticalPanelSimpleListbox)panel).populateWithPublishers();
				}
				else System.err.println("Error: populatePanelsInArrayList found panel of type ListBox with label "+panel.getLabel().getText()+" - don't know how to populate this panel.");
			} else if (panel.getClass() == EditBookVerticalPanelSimpleDate.class) {
				if (panel.getLabel().getText().equals("Publicatiedatum")) {
					((EditBookVerticalPanelSimpleDate)panel).setValue(bookmf.getPublicationDate());
				} else if (panel.getLabel().getText().equals("Eerste publicatiedatum")) {
					((EditBookVerticalPanelSimpleDate)panel).setValue(bookmf.getFirstPublicationDate());
				} else if (panel.getLabel().getText().equals("Datum eerste wijziging")) {					
					((EditBookVerticalPanelSimpleDate)panel).setValue(bookmf.getFirstModificationDate());
				} else if (panel.getLabel().getText().equals("Datum laatste wijziging")) {
					((EditBookVerticalPanelSimpleDate)panel).setValue(bookmf.getModificationDate());
				}
				else System.err.println("Error: populatePanelsInArrayList found panel of type Date with label "+panel.getLabel().getText()+" - don't know how to populate this panel.");
			} else if (panel.getClass() == EditBookVerwijzingenISBNPanel.class) {
				ISBNReference isbnReference = bookmf.getIsbnReferences().get(numIsbnVerwijzingenPanels);
				((EditBookVerwijzingenISBNPanel)panel).setValue(isbnReference);
				numIsbnVerwijzingenPanels ++;
			} else if (panel instanceof EditBookAfmetingenPanel) {
				afmetingenPanel.setHeightInMilimeters(bookmf.getHeight());
				afmetingenPanel.setWidthInMilimeters(bookmf.getWidth());
				afmetingenPanel.setThicknessInMilimeters(bookmf.getThickness());
				afmetingenPanel.setToDisplayMode();
			} else if (panel instanceof EditBookGeillustreerdPanel) {
				geillustreerdPanel.setGeillustreerd(bookmf.isIllustrated());
				if (bookmf.isIllustrated() == true) {
					geillustreerdPanel.setNumBWImages(bookmf.getNumberOfBWIllustrations());
					geillustreerdPanel.setNumColorImages(bookmf.getNumberOfColorIllustrations());
				}
				geillustreerdPanel.setToDisplayMode();
			} else if (panel instanceof EditBookContributorPanel) {
				Contributor c = bookmf.getContributors().get(numMensenPanels);			
				((EditBookContributorPanel)panel).setContributor(c);
				((EditBookContributorPanel)panel).setToDisplayMode();
				numMensenPanels++;
			}
				
		}
		
	}

	
	private ArrayList<EditBookPanel> getRighthandArrayList(PhysicalBookManifestation bookmf) {
		ArrayList<EditBookPanel> rightColumnPanels = new ArrayList<EditBookPanel>();
		String str = "Mensen";

		for (EditBookContributorPanel cp : contributorPanels) {
			cp.setLabel(new Label(str));
			cp.setPersonList(destinationArrayList);
			cp.populatePersonListBox();


			rightColumnPanels.add(cp);
			
			str = "";
		}
	/*	for (Contributor c: bookmf.getContributors()) {
			EditBookContributorPanel panel = new EditBookContributorPanel(str);
			str = "";
			
			rightColumnPanels.add(panel);
		}*/

		EditBookVerticalPanelAddLink addContributor = new EditBookVerticalPanelAddLink(str, this) {
			@Override
			public void addLinkClicked() {
				contributorPanels.add(new EditBookContributorPanel(new String("Mensen"), false));
			//	addNewContributor();
				redrawTable();
			}
		};
		rightColumnPanels.add(addContributor);

		rightColumnPanels.add(uitgeverPanel);
		rightColumnPanels.add(imprintPanel);
		rightColumnPanels.add(beschikbaarCB);
		rightColumnPanels.add(beschikbaarScholtens);
		rightColumnPanels.add(beschikbaarLibris);
		rightColumnPanels.add(beschikbaarUitgever);
		rightColumnPanels.add(vbpPanel);
		rightColumnPanels.add(adviesprijsPanel);
		str = "Onderwerpen";
		for (EditBookSubjectPanel subjectPanel : subjectPanels) {
			subjectPanel.setLabel(new Label(str));
			rightColumnPanels.add(subjectPanel);
			str = "";
		}
		EditBookVerticalPanelAddLink addContentSpecifier = new EditBookVerticalPanelAddLink(str, this) {
			@Override
			public void addLinkClicked() {
				subjectPanels.add(new EditBookSubjectPanel(new String("Onderwerpen"), new ContentSpecifier(), false));
				redrawTable();
			}
		};
		rightColumnPanels.add(addContentSpecifier);
		return rightColumnPanels;
		
	}

	
	
	private ArrayList<EditBookPanel> getLefthandArrayList(PhysicalBookManifestation bookmf) {
		ArrayList<EditBookPanel> leftColumnPanels = new ArrayList<EditBookPanel>();
		leftColumnPanels.add(isbn13Panel);
		leftColumnPanels.add(titelPanel);
		leftColumnPanels.add(subtitelPanel);
		leftColumnPanels.add(publicatiedatumPanel);
		leftColumnPanels.add(eerstepublicatiedatumPanel);
		leftColumnPanels.add(taalPanel);
		leftColumnPanels.add(oorspronkelijketaalPanel);
		leftColumnPanels.add(oorspronkelijkeTitelPanel);
		leftColumnPanels.add(setTitelPanel);
		leftColumnPanels.add(serieTitelPanel);
		// add existing URL verwijzingen panels
		String str = new String("Verwijzingen (URL)");
		for (EditBookVerwijzingenURLPanel urlPanel : urlPanels) {
			urlPanel.setLabel(new Label(str));
			leftColumnPanels.add(urlPanel);
			str = "";
		}
		// add 'add-URL'-panel
		final EditBookDialog thisDialog = this;
		EditBookVerticalPanelAddLink addUrlReference = new EditBookVerticalPanelAddLink(str, this) {
			@Override
			public void addLinkClicked() {
				urlPanels.add(new EditBookVerwijzingenURLPanel(new String("Verwijzingen (URL)"), new URLReference(), false, thisDialog));
				redrawTable();
			}
		};
		leftColumnPanels.add(addUrlReference);
		
		// add existing ISBN verwijzingen panels
		str = new String("Verwijzingen (ISBN)");
		for (EditBookVerwijzingenISBNPanel isbnPanel : isbnPanels) {
			isbnPanel.setLabel(new Label(str));
			leftColumnPanels.add(isbnPanel);
			str = "";
		}
		// add 'add-ISBN'-panel
		EditBookVerticalPanelAddLink addISBNReference = new EditBookVerticalPanelAddLink(str, this) {
			@Override
			public void addLinkClicked() {
				isbnPanels.add(new EditBookVerwijzingenISBNPanel(new String("Verwijzingen (ISBN)"), new ISBNReference(), false, thisDialog));
				redrawTable();
			}
		};
		leftColumnPanels.add(addISBNReference);
		leftColumnPanels.add(productvormPanel);
		leftColumnPanels.add(editiePanel);
		leftColumnPanels.add(drukPanel);
		leftColumnPanels.add(aantalPaginasPanel);
		leftColumnPanels.add(afmetingenPanel);
		leftColumnPanels.add(gewichtPanel);
		leftColumnPanels.add(geillustreerdPanel);
		leftColumnPanels.add(datumEersteWijzigingPanel);
		leftColumnPanels.add(datumLaatsteWijzigingPanel);
		return leftColumnPanels;
	}
	
	/*
		datumEersteWijzigingPanel.setEditable(false);
		datumLaatsteWijzigingPanel.setEditable(false);
		try {
			if (bookmf.getIsbn() == null) {
				System.err.println("getisbN() returned null");
			} else 
			if (bookmf.getIsbn().getIsbn13() == null) {
				System.err.println("getisbN().getIsbn13() returned null");
			}
			isbnPanel.setValue(bookmf.getIsbn().getIsbn13());
		} catch (Exception e) {
			System.err.println("Setvalue ISBN: null");
		}
		//titelPanel.setValue(bookmf.getTitle());
		//if (bookmf.getIsbn() != null) isbnPanel.setValue(bookmf.getIsbn().getIsbn13());
		//if (bookmf.getSubtitle() != null) subtitelPanel.setValue(bookmf.getSubtitle());
		//if (bookmf.getOriginalTitle() != null) oorspronkelijkeTitelPanel.setValue(bookmf.getOriginalTitle());
		//if (bookmf.getSetTitle() != null) setTitelPanel.setValue(bookmf.getSetTitle());
		//if (bookmf.getSeriesTitle() != null) serieTitelPanel.setValue(bookmf.getSeriesTitle());
		aantalPaginasPanel.setValue(bookmf.getNumberOfPages());
		gewichtPanel.setValue(bookmf.getWeight());
		//if (bookmf.getImprint() != null) imprintPanel.setValue(bookmf.getImprint());
		afmetingenPanel.setWidthInMilimeters(bookmf.getWidth());
		afmetingenPanel.setHeightInMilimeters(bookmf.getHeight());
		afmetingenPanel.setThicknessInMilimeters(bookmf.getThickness());
		// extra setToDisplayMode sets the proper label after setting the instance fields. 
		afmetingenPanel.setToDisplayMode();
		geillustreerdPanel.setGeillustreerd(bookmf.isIllustrated());
		geillustreerdPanel.setNumBWImages(bookmf.getNumberOfBWIllustrations());
		geillustreerdPanel.setNumColorImages(bookmf.getNumberOfColorIllustrations());
		geillustreerdPanel.setToDisplayMode();
		if (bookmf.getPublicationDate() != null) publicatiedatumPanel.setValue(bookmf.getPublicationDate());
		if (bookmf.getFirstPublicationDate() != null) eerstepublicatiedatumPanel.setValue(bookmf.getFirstPublicationDate());
		if (bookmf.getFirstModificationDate() != null) datumEersteWijzigingPanel.setValue(bookmf.getFirstModificationDate());
		if (bookmf.getModificationDate() != null) datumLaatsteWijzigingPanel.setValue(bookmf.getModificationDate());

		return leftColumnPanels;

	}

*/

}
